package com.thh.service;

import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;

/**
 * @Author thh
 * @Description
 * @Version 1.0
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class MQService {

    private final Logger logger = LoggerFactory.getLogger(MQService.class);

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;




    @PostConstruct
    public void setup(){
        // 消息发送完毕后，则回调此方法，ack代表发送是否成功
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                // 如果ack为true,代表MQ已经准备收到消息。
                if(!ack){
                    return;
                }
                try {
                    //2:修改本地消息表的状态为："已发送"，删除，修改状态
                    String sql = "update table_distribute_message set msg_status=1 where unique_id=?";
                    int count = jdbcTemplate.update(sql,correlationData.getId());
                    if(count!=1){
                        logger.info("警告：本地消息的状态修改不成功!");
                    }
                    System.out.println("本地消息保存成功!!!");
                }catch (Exception ex){
                    logger.info("警告：修改本地消息表的状态时出现异常!",ex);
                }
            }
        });

    }

    public void sendMsg(JSONObject orderInfo){
        // 发送消息到MQ,CorrelationData当收到消息回执的时候，会附带这个参数
        rabbitTemplate.convertAndSend("","orderQueue",orderInfo.toString(),
                new CorrelationData(orderInfo.getString("orderId")));
    }

}
